const router = require('express').Router()
const validateToken = require('../../../../common/validateToken')
const status_code = require('../../../../common/status_code')
const db = require('../../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../../common/bee/bee')

router.post('/update/info', async (req, resp) => {
  // 错误处理
  const handleError = (errCode, error) => {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  const { id, sex, about, tel, username, mail, status } = req.body
  if (
    !Bee.StringUtils.isNumber(id) ||
    !Bee.StringUtils.isNotBlank(sex) ||
    !Bee.StringUtils.isNumber(status)
  )
    return handleError(10003, '参数错误')

  const [updateUserInfoError, updateUserInfoSuccess] = await to(
    db.query(
      'UPDATE userinfo SET sex=?, about=?, info_updated_time=NOW(), tel=?, username=?, mail=?, status=? WHERE id=?',
      [
        sex,
        about ? about : '',
        tel ? tel : '',
        username ? username : '',
        mail ? mail : '',
        status,
        id,
      ]
    )
  )
  if (updateUserInfoError || !updateUserInfoSuccess)
    return handleError(66013, updateUserInfoError)

  if (updateUserInfoSuccess.affectedRows === 0) {
    return handleError(-1, '系统错误')
  }
  resp.json({
    code: 0,
    msg: status_code[0],
  })
})

module.exports = router
